package com.hxzy.springbootes.controller;

import com.hxzy.springbootes.constants.HotalIndex;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Author gityyge
 * @Description TODO
 * @Date 2023/5/31 14:56
 * @Version 1.0
 */
@RestController
public class HotalIndexController {



    @Autowired
    private RestHighLevelClient  restHighLevelClient;


    @GetMapping(value = "/es/put")
    public String createIndex(String indexName) throws IOException {
        // 1.创建Request对象
        GetIndexRequest request = new GetIndexRequest(indexName);
        // 2.发送请求
        boolean exists = this.restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);

        if(exists){
            return "已存在索引库"+indexName+",不能创建";
        }else{
            // 1.创建Request对象
            CreateIndexRequest putRequest = new CreateIndexRequest(indexName);
            // 2.准备请求的参数：DSL语句
            putRequest.source(HotalIndex.HOTAL_INDEX_SQL, XContentType.JSON);
            // 3.发送请求
            CreateIndexResponse createIndexResponse = this.restHighLevelClient.indices().create(putRequest, RequestOptions.DEFAULT);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            return acknowledged?"创建索引库成功": "创建索引库失败";
        }
    }

    /**
     * 删除索引库
     * @param indexName
     * @return
     */
    @DeleteMapping(value = "/es/{indexName}")
    public String deleteIndex(@PathVariable(value = "indexName") String indexName) throws IOException {
        //1、 发送Delete请求
        DeleteIndexRequest  deleteIndexRequest=new DeleteIndexRequest(indexName);
        AcknowledgedResponse acknowledgedResponse = this.restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);

        return acknowledgedResponse.isAcknowledged()?"删除成功":"删除失败";
    }




}
